class Product < ActiveRecord::Base
	belongs_to :category
	belongs_to :label
	belongs_to :item_type, :class_name => 'Type'
	has_one :image, :as => :owner
	validates_presence_of :name, :short_description, :description
	validates_uniqueness_of :name
	money :price
	
	after_save :set_product_to_image
	
	def uploaded_image
		image || self.build_image
	end
	
	def uploaded_data=(data)
		uploaded_image.uploaded_data = data unless data.blank?
	end
	
	def uploaded_data
		uploaded_image.uploaded_data
	end
	
	class << self
		
		def find_by_category( category_id, type_id, limit = 10 )
			paginate_by_sql( [FIND_BY_CATEGORY_SQL, category_id, category_id, type_id ], :page => 1, :per_page => 10 )
		end
	
		def find_random
			find( :first, :order => 'rand()' )
		end
		
	end
	
	private
	
	def set_product_to_image
		if image
			image.owner = self
			image.save!
		end
	end
	
	FIND_BY_CATEGORY_SQL = %Q{ select p.* from products p, categories c where ((c.id = p.category_id and c.id = ?) or (c.category_id = p.category_id and c.category_id = ?)) and p.item_type_id = ? order by rand() }
	
end
